package com.ruoyi.planthopper.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.ImageProcessingException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.planthopper.domain.*;
import com.ruoyi.planthopper.mapper.InvesMapper;
import com.ruoyi.planthopper.mapper.PlotMapper;
import com.ruoyi.planthopper.service.InvesService;
import com.ruoyi.utils.FileTool;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseString;
import com.ruoyi.utils.PicUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @program: class by cxf
 * @author: AbrahamBill
 * @date: 2022/7/22
 **/
@Slf4j
@RestController
public class InvesController extends BaseController {
    @Autowired
    private InvesMapper investigateMapper;

    @Autowired
    private PlotMapper plotMapper;

    @Autowired
    private InvesService invesService;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionUrl}")
    private String detectionUrl;
    @GetMapping("/selectPlotNameByUser")
    public AjaxResult retPlotNameLst(String userName){
        List<String> res = investigateMapper.selectPlotNameByUser(userName);
        List<String> ret = new ArrayList<>();
        for(String s:res){
            if(!ret.contains(s)){
                ret.add(s);
            }
        }
//        List<String> ret = res.stream().distinct().collect(Collectors.toList());
        Collections.reverse(ret);
        return AjaxResult.success(ret);
    }
    @GetMapping("/selectPlotNameByUser2")
    public AjaxResult retPlotNameLst2(String userName){
        List<WebPlotInfo> res = invesService.selectPlotNameByUser2(userName);
        List<WebPlotInfo> ret = new ArrayList<>();
        for(WebPlotInfo s:res){
            if(!ret.contains(s)){
                ret.add(s);
            }
        }
        Collections.reverse(ret);
        return AjaxResult.success(ret);
    }

    @PostMapping("/deletePlotById")
    public AjaxResult deletPlotById(int id){
        try{
            int res = invesService.deleteMyPlotById(id);
            if(res==1){
                return AjaxResult.success("成功删除!");
            }else{
                return AjaxResult.success("删除失败!");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }
    /**
     * 获取所有调查信息
     */
    @GetMapping("/selectAllInvestigateInfo")
    public AjaxResult retAllInvestigateInfo(){
        List<InvesInfo> all_info = investigateMapper.selectInvesList(null);
        for(InvesInfo info:all_info){
            info.initDisplayFileName();
        }
        return AjaxResult.success(all_info);
    }
    /**
     * 根据条件调查信息(详细的每一条记录)
     */
    @GetMapping("/getInvestigateInfoByCondition")
    public AjaxResult retInvestigateInfoByCondition(QueryCondition queryCondition){
//        QueryWrapper<InvestigateInfo> query = new QueryWrapper<>();
//        if((!"".equals(queryCondition.getBeginTime()))&&(!"".equals(queryCondition.getEndTime()))){
//            query.between("time",queryCondition.getBeginTime(),queryCondition.getEndTime());
//        }else if("".equals(queryCondition.getBeginTime())&&(!"".equals(queryCondition.getEndTime()))){
//            query.le("time", queryCondition.getEndTime());
//        }else if((!"".equals(queryCondition.getBeginTime()))&&"".equals(queryCondition.getEndTime())){
//            query.ge("time", queryCondition.getBeginTime());
//        }
//        query.eq(StringUtils.isNotEmpty(queryCondition.getProvince()),"province",queryCondition.getProvince());
//        query.eq(StringUtils.isNotEmpty(queryCondition.getCity()),"city",queryCondition.getCity());
//        query.eq(StringUtils.isNotEmpty(queryCondition.getDistrict()),"district",queryCondition.getDistrict());
//        query.eq(StringUtils.isNotEmpty(queryCondition.getPlotName()),"plotName",queryCondition.getPlotName());
//        query.eq(StringUtils.isNotEmpty(queryCondition.getPlanthopperCategory()),"planthopperCategory", queryCondition.getPlanthopperCategory());
//        query.eq(StringUtils.isNotEmpty(queryCondition.getInvestigator()),"Investigator",queryCondition.getInvestigator());
        List<InvesInfo> lst = investigateMapper.selectInvesList(queryCondition);
        for(InvesInfo info:lst){
            info.initDisplayFileName();
        }
        return AjaxResult.success(lst);
    }

    @GetMapping("/getInvestigateInfoByCondition2")
    public TableDataInfo getImgs(QueryCondition queryCondition){
        startPage();
        List<InvesInfo> lst = invesService.selectInvesListWeb(queryCondition);
        return getDataTable(lst);
    }

    @PostMapping("/deleteImgById")
    public AjaxResult deleteImgById(int id){
        try{
            int res = invesService.deleteMyImgById(id);
            if(res==1){
                return AjaxResult.success("成功删除!");
            }else{
                return AjaxResult.error("删除失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/deleteInvesInfoById")
    public AjaxResult deleteInvesInfoById(int id){
        try{
            int res = invesService.deleteInvesInfoById(id);
            if(res==1){
                return AjaxResult.success("成功删除!");
            }else{
                return AjaxResult.error("删除失败");
            }
        }catch (Exception e){
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/insertNewInvestigateInfo")
    public AjaxResult insertNewInvestigateInfo(InvesInfo investigateInfo, @RequestParam("imageName") MultipartFile[] files) throws IOException, ImageProcessingException, ParseException {
        //首先检测地块是否存在，不存在则进行地块的新增
        if (investigateInfo.getPlotName() != null) {
            PlotInfo plotInfo = new PlotInfo();
            plotInfo.setProvince(investigateInfo.getProvince());
            plotInfo.setCity(investigateInfo.getCity());
            plotInfo.setDistrict(investigateInfo.getDistrict());
            plotInfo.setPlotName(investigateInfo.getPlotName());
            plotInfo.setAddress(investigateInfo.getAddress());
            plotInfo.setUserName(investigateInfo.getUserName());
            List<PlotInfo> lst = plotMapper.selectPlotList(plotInfo);
            if (lst == null || lst.isEmpty()) {
                plotMapper.insertPlot(plotInfo);
            }
        }
        //对图像进行识别，处理信息，插入调查信息
        for (MultipartFile myfile : files) {
//            PicUtil.correctImg();
            File tmp_f = PicUtil.multipartFileToFile(myfile);
            PicUtil.correctImg(tmp_f.getPath());
            FileInputStream file_input_stream = new FileInputStream(tmp_f);
            MultipartFile file = new MockMultipartFile(tmp_f.getName(),tmp_f.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(),file_input_stream);
            // 如果图片不为空
            if (!file.isEmpty()) {
                String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
                //为linux服务---------------------------
                String detectionImages = StringUtils.substringAfter(images, "profile");
                File imgFile = new File(profile + detectionImages);
                String imgCreateTime = FileTool.getImgCreateTime(imgFile);
                List<DetectionInfo> detectionInfos = new ArrayList<>();
                ImgDrawCircleTool tool = new ImgDrawCircleTool();
                //调用模型检测接口进行检测并返回结果
                try {
                    // 图片发送到Django进行识别
                    ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
                    log.info("responseEntity------->" + responseEntity.getBody());
                    // json格式的数据转换成数组格式
                    detectionInfos = JSON.parseArray(responseEntity.getBody(), DetectionInfo.class);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
                // 有检测结果的情况
                if (detectionInfos.size() != 0) {
                    for (DetectionInfo info : detectionInfos) {
                        if (StringUtils.isNotNull(info)) {
                            info.setImagePath(images);
                            info.setOriginalFileName(file.getOriginalFilename());
                            info.setThumPath(images.replace("original", "thum"));
                            System.out.println(info.getTag());
                            String tagNum = ParseString.getTagNum(info.getTag());
                            log.info("检测结果：" + tagNum);
                            //detection.getTag()  [2,2,2,2,2,2,2,3,3,2,2,3]
                            //tagNum  {"2":9,"3":3}
                            JSONObject jsonObject = JSON.parseObject(tagNum);
                            int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0, num_5=0,num_6=0,num_7=0,num_8=0;
                            int num_9 = 0, num_10 = 0, num_11 = 0, num_12 = 0, num_13=0,num_14=0,num_15=0;
                            if (jsonObject.get("1") != null) {
                                num_1 = (int) jsonObject.get("1");
                            }
                            if (jsonObject.get("2") != null) {
                                num_2 = (int) jsonObject.get("2");
                            }
                            if (jsonObject.get("3") != null) {
                                num_3 = (int) jsonObject.get("3");
                            }
                            if (jsonObject.get("4") != null) {
                                num_4 = (int) jsonObject.get("4");
                            }
                            if (jsonObject.get("5") != null) {
                                num_5 = (int) jsonObject.get("5");
                            }
                            if (jsonObject.get("6") != null) {
                                num_6 = (int) jsonObject.get("6");
                            }
                            if (jsonObject.get("7") != null) {
                                num_7 = (int) jsonObject.get("7");
                            }
                            if (jsonObject.get("8") != null) {
                                num_8 = (int) jsonObject.get("8");
                            }
                            if (jsonObject.get("9") != null) {
                                num_9 = (int) jsonObject.get("9");
                            }
                            if (jsonObject.get("10") != null) {
                                num_10 = (int) jsonObject.get("10");
                            }
                            if (jsonObject.get("11") != null) {
                                num_11 = (int) jsonObject.get("11");
                            }
                            if (jsonObject.get("12") != null) {
                                num_12 = (int) jsonObject.get("12");
                            }
                            if (jsonObject.get("13") != null) {
                                num_13 = (int) jsonObject.get("13");
                            }
                            if (jsonObject.get("14") != null) {
                                num_14 = (int) jsonObject.get("14");
                            }
                            if (jsonObject.get("15") != null) {
                                num_15 = (int) jsonObject.get("15");
                            }

                            /*画框之后的结果图 resUrl  缩略图 已添加 */
                            List<String> tagList = JSON.parseArray(info.getTag(), String.class);
                            //下面开始绘制结果的图像
                            String resultPath = tool.doDrawRectangle(info.getCorner(), tagList, profile + detectionImages, num_1, num_2, num_3, num_4,num_5,num_6,num_7,num_8,num_9,num_10,num_11,num_12,num_13,num_14,num_15).replace(profile, Constants.RESOURCE_PREFIX);
                            info.setTag(ParseString.getTagNum(info.getTag()));
                            info.setResultPath(resultPath);
                            info.setImgTime(imgCreateTime);
                            log.info(info.toString());
                            //下面开始将所有信息插入到investigateInfo中
                            investigateInfo.setImgPath(images);
                            investigateInfo.setTime(getTimeStr());
                            investigateInfo.setTag(info.getTag());
                            // 以下为处理图片路径问题
                            String imageName = investigateInfo.getImgPath().split("/")[investigateInfo.getImgPath().split("/").length - 1];
                            imageName = imageName.split("__")[0];
                            String ImagePathOld = investigateInfo.getImgPath();
                            imageName += "__" + ImagePathOld.split("__")[ImagePathOld.split("__").length - 1];
                            String imagePathOldThum = ImagePathOld.replace("original", "thum");
                            String imagePathOldResult = ImagePathOld.replace("original", "original__Result");
                            File oldFile = new File(ImagePathOld);
                            File oldFileThum = new File(imagePathOldThum);
                            File oldFileResult = new File(imagePathOldResult);
                            String path = ImagePathOld.replace(ImagePathOld.split("/")[ImagePathOld.split("/").length - 1], "");
                            String newImagePath = path + imageName;
                            String newImagePathThum = newImagePath.replace("original", "thum");
                            String newImagePathResult = newImagePath.replace("original", "original__Result");
                            File newFile = new File(newImagePath);
                            File newFileThum = new File(newImagePathThum);
                            File newFileResult = new File(newImagePathResult);
                            oldFile.renameTo(newFile);
                            oldFileThum.renameTo(newFileThum);
                            oldFileResult.renameTo(newFileResult);
                            newImagePath = newImagePath.replace("\\", "/");
                            newImagePathThum = newImagePathThum.replace("\\", "/");
                            newImagePathResult = newImagePathResult.replace("\\", "/");
                            investigateInfo.setImgPath(newImagePath);
                            investigateInfo.setThumPath(newImagePathThum);
                            investigateInfo.setResultPath(newImagePathResult);
                            //将一张图片的完整调查信息插入（目前还差tags的解析，各种虫的数目、总数的插入）
                            // num1:长翅飞虱 num2:高龄若虫 num3:低龄若虫 num4:短翅飞虱
                            // new: num1:高龄若虫 num2:低龄若虫 num3:长翅飞虱 num4:短翅飞虱
                            /*
                            长翅飞虱	M-adult
                            短翅飞虱	B-adult
                            低龄若虫	J-nymph
                            高龄若虫	S-nymph
                            */
                            investigateInfo.setMBphAdult(num_1);
                            investigateInfo.setBBphAdult(num_2);
                            investigateInfo.setSBphNymph(num_3);
                            investigateInfo.setMWbphAdult(num_4);
                            investigateInfo.setBWbphAdult(num_5);
                            investigateInfo.setSWbphNymph(num_6);
                            investigateInfo.setJRphNymph(num_7);
                            investigateInfo.setMSbphAdult(num_8);
                            investigateInfo.setBSbphAdult(num_9);
                            investigateInfo.setSSbphNymph(num_10);
                            investigateInfo.setSpider(num_11);
                            investigateInfo.setMiridae(num_12);
                            investigateInfo.setRoveBeetle(num_13);
                            investigateInfo.setRlhAdult(num_14);
                            investigateInfo.setRlhNymph(num_15);
                            int sum = num_1+num_2+num_3+num_4+num_5+num_6+num_7+num_8+num_9+num_10+num_11+num_12+num_13+num_14+num_15;
                            investigateInfo.setSum(sum);
                            investigateInfo.setInsertDate(getDate());
                            int ret_num = investigateMapper.insertInvesInfo(investigateInfo);
                            if (ret_num<=0){
                                return AjaxResult.error("插入数据库失败!");
                            }
                        }
                    }
                }
                // 没有检测结果的情况
                else {
                    String resultPath = tool.doDrawEmpty(profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                    investigateInfo.setImgPath(images);
                    investigateInfo.setTime(getTimeStr());
                    investigateInfo.setTag("{}");
                    //以下为处理图片路径问题
                    String imageName = investigateInfo.getImgPath().split("/")[investigateInfo.getImgPath().split("/").length - 1];
                    imageName = imageName.split("__")[0];
                    String ImagePathOld = investigateInfo.getImgPath();
                    imageName += "__" + ImagePathOld.split("__")[ImagePathOld.split("__").length - 1];
                    String imagePathOldThum = ImagePathOld.replace("original", "thum");
                    String imagePathOldResult = ImagePathOld.replace("original", "original__Result");
                    File oldFile = new File(ImagePathOld);
                    File oldFileThum = new File(imagePathOldThum);
                    File oldFileResult = new File(imagePathOldResult);
                    String path = ImagePathOld.replace(ImagePathOld.split("/")[ImagePathOld.split("/").length - 1], "");
                    String newImagePath = path + imageName;
                    String newImagePathThum = newImagePath.replace("original", "thum");
                    String newImagePathResult = newImagePath.replace("original", "original__Result");
                    File newFile = new File(newImagePath);
                    File newFileThum = new File(newImagePathThum);
                    File newFileResult = new File(newImagePathResult);
                    oldFile.renameTo(newFile);
                    oldFileThum.renameTo(newFileThum);
                    oldFileResult.renameTo(newFileResult);
                    newImagePath = newImagePath.replace("\\", "/");
                    newImagePathThum = newImagePathThum.replace("\\", "/");
                    newImagePathResult = newImagePathResult.replace("\\", "/");
                    investigateInfo.setImgPath(newImagePath);
                    investigateInfo.setThumPath(newImagePathThum);
                    investigateInfo.setResultPath(newImagePathResult);
                    //将一张图片的完整调查信息插入（目前还差tags的解析，各种虫的数目、总数的插入）
                    // num1:长翅飞虱 num2:高龄若虫 num3:低龄若虫 num4:短翅飞虱
                    investigateInfo.setSum(0);
                    investigateInfo.setMBphAdult(0);
                    investigateInfo.setBBphAdult(0);
                    investigateInfo.setSBphNymph(0);
                    investigateInfo.setMWbphAdult(0);
                    investigateInfo.setBWbphAdult(0);
                    investigateInfo.setSWbphNymph(0);
                    investigateInfo.setJRphNymph(0);
                    investigateInfo.setMSbphAdult(0);
                    investigateInfo.setBSbphAdult(0);
                    investigateInfo.setSSbphNymph(0);
                    investigateInfo.setSpider(0);
                    investigateInfo.setMiridae(0);
                    investigateInfo.setRoveBeetle(0);
                    investigateInfo.setRlhAdult(0);
                    investigateInfo.setRlhNymph(0);
                    investigateInfo.setInsertDate(getDate());
                    int ret_num = investigateMapper.insertInvesInfo(investigateInfo);
                    if (ret_num<=0){
                        return AjaxResult.error("插入数据库失败!");
                    }
                }
                //如果上传的图片为空，说明上传图片失败了
            }else{
                return AjaxResult.error("上传图片异常！");
            }
        }
        return AjaxResult.success("新增调查信息成功！", investigateInfo);
    }
    private String getTimeStr(){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }

    private String getDate(){
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        return formatter.format(date);
    }
}
